package group

import (
	"common/models"
	"common/validate"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/docModel"
	"strings"
)

func (h GHandler) UpdateGroupInfo(c *gin.Context) {
	resp := new(models.RespData)
	req := new(docModel.UpdateGroupInfoReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Group:UpdateGroupInfo with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Group:UpdateGroupInfo with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	var (
		changList []string
		changMap  map[string]struct{}
	)
	changMap = make(map[string]struct{})
	info, err := h.M.GroupSelectByID(req.ID)
	if err != nil {
		zap.L().Error("Group:UpdateGroupInfo  h.M.GroupSelectByID", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	oldList := strings.Split(info.Peoples, "|")
	newList := strings.Split(req.Peoples, "|")
	for _, s := range newList {
		changMap[s] = struct{}{}
	}
	info.Name = req.Name
	info.Peoples = req.Peoples
	info.Text = req.Text
	info.Managers = req.Managers
	info.ImgId = req.ImgId
	info.ImgSrc = req.ImgSrc
	//更新
	err = h.M.GroupSaveByID(info)
	if err != nil {
		zap.L().Error("Group:UpdateGroupInfo   h.M.GroupSaveByID", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	//更新这次删除的人
	for _, s := range oldList {
		if _, ok := changMap[s]; !ok {
			changList = append(changList, s)
		}
	}
	//删除对应的人
	for _, s := range changList {
		h.delUserToGroup(s, req.ID)
	}
	resp.SendSuccess(c)
}

func (h GHandler) delUserToGroup(id, groupID string) (err error) {
	//获得用户的信息
	exist, info, err := h.M.UserCheckId(id)
	if err != nil {
		zap.L().Error("Group:UpdateGroupInfo   h.M.GroupSaveByID", zap.Error(err))
		return
	}
	if exist {
		groups := strings.Split(info.Groups, "|")
		info.Groups = models.RemoveList(groupID, groups)
		//更新用户
		err = h.M.UserSaveById(info)
		if err != nil {
			zap.L().Error("Group:UpdateGroupInfo   h.M.GroupSaveByID", zap.Error(err))
			return
		}
	}
	return
}
func (h GHandler) DelGroup(c *gin.Context) {
	resp := new(models.RespData)
	req := new(docModel.DelGroupReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Group:DelGroup with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Group:DelGroup with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	err := h.M.GroupDelByID(req.GroupID)
	if err != nil {
		zap.L().Error("Group:UpdateGroupInfo   h.M.GroupSaveByID", zap.Error(err))
		return
	}
	resp.SendSuccess(c)
	return
}
